import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Space, 
  Modal, 
  Form, 
  Input, 
  Select, 
  message, 
  Tag,
  Tooltip,
  Popconfirm
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  SearchOutlined,
  ReloadOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Option } = Select;

interface DictType {
  id: string;
  dictName: string;
  dictType: string;
  status: '0' | '1';
  remark: string;
  createTime: string;
}

interface DictData {
  id: string;
  dictType: string;
  dictLabel: string;
  dictValue: string;
  dictSort: number;
  status: '0' | '1';
  remark: string;
  createTime: string;
}

const Dict: React.FC = () => {
  // 状态管理
  const [dictTypeList, setDictTypeList] = useState<DictType[]>([]);
  const [dictDataList, setDictDataList] = useState<DictData[]>([]);
  const [selectedDictType, setSelectedDictType] = useState<string>('');
  const [typeModalVisible, setTypeModalVisible] = useState(false);
  const [dataModalVisible, setDataModalVisible] = useState(false);
  const [typeForm] = Form.useForm();
  const [dataForm] = Form.useForm();
  const [loading, setLoading] = useState(false);

  // 模拟数据
  useEffect(() => {
    // 模拟获取字典类型列表
    const mockDictTypes: DictType[] = [
      {
        id: '1',
        dictName: '用户性别',
        dictType: 'sys_user_sex',
        status: '0',
        remark: '用户性别列表',
        createTime: '2024-01-01 12:00:00'
      },
      {
        id: '2',
        dictName: '系统开关',
        dictType: 'sys_normal_disable',
        status: '0',
        remark: '系统开关列表',
        createTime: '2024-01-01 12:00:00'
      }
    ];
    setDictTypeList(mockDictTypes);

    // 模拟获取字典数据列表
    const mockDictData: DictData[] = [
      {
        id: '1',
        dictType: 'sys_user_sex',
        dictLabel: '男',
        dictValue: '0',
        dictSort: 1,
        status: '0',
        remark: '性别男',
        createTime: '2024-01-01 12:00:00'
      },
      {
        id: '2',
        dictType: 'sys_user_sex',
        dictLabel: '女',
        dictValue: '1',
        dictSort: 2,
        status: '0',
        remark: '性别女',
        createTime: '2024-01-01 12:00:00'
      }
    ];
    setDictDataList(mockDictData);
  }, []);

  // 字典类型列定义
  const typeColumns: ColumnsType<DictType> = [
    {
      title: '字典名称',
      dataIndex: 'dictName',
      key: 'dictName',
    },
    {
      title: '字典类型',
      dataIndex: 'dictType',
      key: 'dictType',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === '0' ? 'success' : 'error'}>
          {status === '0' ? '正常' : '停用'}
        </Tag>
      ),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEditType(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            icon={<SearchOutlined />}
            onClick={() => handleViewData(record)}
          >
            数据
          </Button>
          <Popconfirm
            title="确定要删除该字典类型吗？"
            icon={<ExclamationCircleOutlined />}
            onConfirm={() => handleDeleteType(record)}
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 字典数据列定义
  const dataColumns: ColumnsType<DictData> = [
    {
      title: '字典标签',
      dataIndex: 'dictLabel',
      key: 'dictLabel',
    },
    {
      title: '字典键值',
      dataIndex: 'dictValue',
      key: 'dictValue',
    },
    {
      title: '字典排序',
      dataIndex: 'dictSort',
      key: 'dictSort',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === '0' ? 'success' : 'error'}>
          {status === '0' ? '正常' : '停用'}
        </Tag>
      ),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEditData(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除该字典数据吗？"
            icon={<ExclamationCircleOutlined />}
            onConfirm={() => handleDeleteData(record)}
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理字典类型相关操作
  const handleAddType = () => {
    typeForm.resetFields();
    setTypeModalVisible(true);
  };

  const handleEditType = (record: DictType) => {
    typeForm.setFieldsValue(record);
    setTypeModalVisible(true);
  };

  const handleDeleteType = (record: DictType) => {
    setDictTypeList(dictTypeList.filter(item => item.id !== record.id));
    message.success('删除成功');
  };

  const handleTypeModalOk = () => {
    typeForm.validateFields().then(values => {
      const newType: DictType = {
        id: values.id || Math.random().toString(36).substr(2, 9),
        ...values,
        createTime: new Date().toLocaleString()
      };
      
      if (values.id) {
        setDictTypeList(dictTypeList.map(item => 
          item.id === values.id ? newType : item
        ));
        message.success('更新成功');
      } else {
        setDictTypeList([...dictTypeList, newType]);
        message.success('添加成功');
      }
      
      setTypeModalVisible(false);
    });
  };

  // 处理字典数据相关操作
  const handleViewData = (record: DictType) => {
    setSelectedDictType(record.dictType);
    // 这里应该根据dictType获取对应的字典数据
  };

  const handleAddData = () => {
    if (!selectedDictType) {
      message.warning('请先选择字典类型');
      return;
    }
    dataForm.resetFields();
    setDataModalVisible(true);
  };

  const handleEditData = (record: DictData) => {
    dataForm.setFieldsValue(record);
    setDataModalVisible(true);
  };

  const handleDeleteData = (record: DictData) => {
    setDictDataList(dictDataList.filter(item => item.id !== record.id));
    message.success('删除成功');
  };

  const handleDataModalOk = () => {
    dataForm.validateFields().then(values => {
      const newData: DictData = {
        id: values.id || Math.random().toString(36).substr(2, 9),
        dictType: selectedDictType,
        ...values,
        createTime: new Date().toLocaleString()
      };
      
      if (values.id) {
        setDictDataList(dictDataList.map(item => 
          item.id === values.id ? newData : item
        ));
        message.success('更新成功');
      } else {
        setDictDataList([...dictDataList, newData]);
        message.success('添加成功');
      }
      
      setDataModalVisible(false);
    });
  };

  return (
    <div className="dict-container">
      <Card title="字典类型" className="dict-type-card">
        <div className="table-operations">
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAddType}
            >
              新增
            </Button>
            <Button
              icon={<ReloadOutlined />}
              onClick={() => setLoading(true)}
            >
              刷新
            </Button>
          </Space>
        </div>
        <Table
          columns={typeColumns}
          dataSource={dictTypeList}
          rowKey="id"
          loading={loading}
          pagination={{
            total: dictTypeList.length,
            pageSize: 10,
            showTotal: (total) => `共 ${total} 条`
          }}
        />
      </Card>

      <Card 
        title="字典数据" 
        className="dict-data-card"
        extra={
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAddData}
          >
            新增
          </Button>
        }
      >
        <Table
          columns={dataColumns}
          dataSource={dictDataList}
          rowKey="id"
          loading={loading}
          pagination={{
            total: dictDataList.length,
            pageSize: 10,
            showTotal: (total) => `共 ${total} 条`
          }}
        />
      </Card>

      {/* 字典类型表单弹窗 */}
      <Modal
        title="字典类型"
        open={typeModalVisible}
        onOk={handleTypeModalOk}
        onCancel={() => setTypeModalVisible(false)}
      >
        <Form
          form={typeForm}
          layout="vertical"
        >
          <Form.Item
            name="dictName"
            label="字典名称"
            rules={[{ required: true, message: '请输入字典名称' }]}
          >
            <Input placeholder="请输入字典名称" />
          </Form.Item>
          <Form.Item
            name="dictType"
            label="字典类型"
            rules={[{ required: true, message: '请输入字典类型' }]}
          >
            <Input placeholder="请输入字典类型" />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Option value="0">正常</Option>
              <Option value="1">停用</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="remark"
            label="备注"
          >
            <Input.TextArea placeholder="请输入备注" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 字典数据表单弹窗 */}
      <Modal
        title="字典数据"
        open={dataModalVisible}
        onOk={handleDataModalOk}
        onCancel={() => setDataModalVisible(false)}
      >
        <Form
          form={dataForm}
          layout="vertical"
        >
          <Form.Item
            name="dictLabel"
            label="字典标签"
            rules={[{ required: true, message: '请输入字典标签' }]}
          >
            <Input placeholder="请输入字典标签" />
          </Form.Item>
          <Form.Item
            name="dictValue"
            label="字典键值"
            rules={[{ required: true, message: '请输入字典键值' }]}
          >
            <Input placeholder="请输入字典键值" />
          </Form.Item>
          <Form.Item
            name="dictSort"
            label="字典排序"
            rules={[{ required: true, message: '请输入字典排序' }]}
          >
            <Input type="number" placeholder="请输入字典排序" />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Option value="0">正常</Option>
              <Option value="1">停用</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="remark"
            label="备注"
          >
            <Input.TextArea placeholder="请输入备注" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Dict; 